const gulp = require('gulp'),
	clean = require('gulp-clean'),
	sass = require('gulp-sass')(require('sass')),
	babel = require('gulp-babel'),
	plumber = require("gulp-plumber"),
	marked = require('gulp-marked'),
	rename = require('gulp-rename'),
	uglify = require("gulp-uglify"),
	cssm = require("gulp-clean-css"),
	imagemin = require('gulp-imagemin'),
	browserSync = require('browser-sync').create(),
	prefixer = require('gulp-autoprefixer'),
	beautify = require('gulp-beautify');
	spritesmith = require('gulp.spritesmith'),
    template = require('gulp-art-tpl'),
	newdir = (new Date()).valueOf();
// 引入配置文件
sass.compiler = require('node-sass');
const config = require('../config/config.json');

const {handle_path} = require('./handle_path.js')


// build --env test 开发环境
// build --env pro 生产环境
const outDir = !process.title.includes('debug') ? 'build/' : 'dist/';
const jsOutDir = outDir + "js";
const libsOutDir = outDir +"libs";
const imgOutDir = outDir + "images";
const cssOutDir = outDir + "css";
const fontsOutDir = outDir + "fonts";
/**
 * @description 拷贝图片资源
 * @returns 
 */
const copyImgHandler = function () {
	return gulp.src(handle_path['copy_img'])
		.pipe(plumber())
		.pipe(rename({
			dirname: ''
		}))
		.pipe(gulp.dest(imgOutDir));

}
exports.copyImgHandler = copyImgHandler
/**
 * @description 拷贝iconfonts
 * @returns 
 */
const fontsHandler = function () {
	return gulp.src(handle_path['font'])
		.pipe(plumber())
		.pipe(rename({
			dirname: ''
		}))
		.pipe(gulp.dest(fontsOutDir));

}
exports.fontsHandler = fontsHandler
/**
 * @description 拷贝编译后的js
 * @returns 
 */
const copyJsHandler = function () {
	return gulp.src(handle_path['copy_js'])
		.pipe(plumber())
		.pipe(rename({
			dirname: ''
		}))
		.pipe(gulp.dest(jsOutDir))
}
exports.copyJsHandler = copyJsHandler;


/**
 * 复制favicon
 */
const copyFavHandler = function () {
	return gulp.src(handle_path['copy_ficon'])
		.pipe(gulp.dest(outDir));
}
exports.copyFavHandler = copyFavHandler;
/**
 * @description 拷贝第三方库
 * @returns   todo!
 */
const libsHandler = function () {
	return gulp.src(handle_path['copy_lib'])
		.pipe(plumber())
		.pipe(gulp.dest(libsOutDir))
}

exports.libsHandler = libsHandler
/**
 * @description scss编译
 * @returns
 */
const scssHandler = function () {
	return gulp.src(handle_path['scss'])
		.pipe(sass({ outputStyle: 'compact' }).on('error', sass.logError))//compact:紧凑单行模式，compressed：压缩一行模式
		.pipe(plumber())
		.pipe(rename({
			dirname: ''
		}))
		.pipe(prefixer({
			overrideBrowserslist: ['last 2 versions'],
			cascade: true,
			remove: true //是否去掉不必要的前缀 默认：true
		}))
		.pipe(gulp.dest(cssOutDir))
}
exports.scssHandler = scssHandler

/**
 * @description dist清空
 * @returns 
 */
exports.cleanDist = function () {
	return gulp.src(["dist/"], {
		allowEmpty: true
	}).pipe(clean());
}

/**
 * @description build构建清空
 * @returns 
 */
exports.cleanAll = function () {
	return gulp.src(['build/'], {
		allowEmpty: true
	}).pipe(clean());
}

/**
 * @description babel转换
 * @returns 
 */
const babelHandler = function () {
	return gulp.src(handle_path['js']).pipe(plumber({
		errorHandler: function (e) {
			console.info("----------------es6语法有误，导致babel转换失败start-----------");
			console.info(marked(e.message));
			console.info("----------------es6语法有误，导致babel转换失败end-----------");
		}
	}))
		.pipe(rename({
			dirname: ''
		}))
		.pipe(babel({
			presets: ['@babel/env']
		}))
		.pipe(gulp.dest(jsOutDir))
}
exports.babelHandler = babelHandler


/**
 * @description js压缩
 * @returns 
 */
const jsHandler = function () {
	return gulp.src(handle_path['js'])
		.pipe(uglify())
		.pipe(gulp.dest(jsOutDir));
}
exports.jsHandler = jsHandler;
/**
 * @description css压缩
 * @returns 
 */
const cssHandler = function () {
	return gulp.src(handle_path['css'])
		.pipe(plumber())
		.pipe(cssm({
			compatibility: 'ie8',
			keepSpecialComments: '*'
		}))
		.pipe(gulp.dest(cssOutDir));
}
exports.cssHandler = cssHandler;
/**
 * @description 图片压缩
 * @returns 
 */
const imgHandler = function () {
	return gulp.src(handle_path['img'])
		.pipe(imagemin([
			imagemin.gifsicle({ interlaced: true }),
			// imagemin.mozjpeg({ quality: 75, progressive: true }),
			imagemin.optipng({ optimizationLevel: 6 }),
			imagemin.svgo({
				plugins: [
					{ removeViewBox: true },
					{ cleanupIDs: false }
				]
			})
		]))
		.pipe(gulp.dest(imgOutDir))
}
exports.imgHandler = imgHandler

/**
 * @description 雪碧图生成
 * @returns 
 * 使用情况，对一个固定宽高的div使用
 */
const spriteHandler = function () {
	return gulp.src(handle_path['sprit'])
		.pipe(spritesmith({
			imgName: 'sprite.png',//保存合并后图片的地址
			cssName: 'sprite.css',//保存合并后对于css样式的地址
			padding: 0,//合并时两个图片的间距
			cssTemplate: data => {
				var arr = [];
				data.sprites.forEach(sprite => {
					arr.push(
						".sprite-" + sprite.name +
						"{" +
						"background-image: url(../images/" + sprite.escaped_image + ");" +
						'background-size:' + sprite.total_width + 'px ' + sprite.total_height + 'px;' +
						"background-position: " + sprite.offset_x + 'px ' + sprite.offset_y + 'px;' +
						"width:" + sprite.width + "px;" +
						"height:" + sprite.height + "px;" +
						"}\n");
				});
				return arr.join("");
			}

		}))
		.pipe(gulp.dest(imgOutDir + '/px-' + newdir + ''))
}
exports.spriteHandler = spriteHandler

gulp.task('delete', (cb) => {
	return del(['dest/*'], cb);
});
/**
 * @description 静态页面编译
 * @returns 
 */
const htmlHandler = function () {
	return gulp.src(handle_path['html'])
		.pipe(plumber())
		.pipe(template({
				config //config页面变量
			}
		))
		.pipe(beautify.html({ indent_size: 2 }))
		.pipe(rename({
			dirname: ''
		}))
		.pipe(gulp.dest(outDir));
}
exports.htmlHandler = htmlHandler;

/**
 * @description 本地web服务器
 * @returns 
 */
exports.servicetHandler = function () {
	browserSync.init({
		port: config.serverPort,
		server: {
			baseDir: 'dist/',
			directory: true,
			middleware: function (req, res, next) {
				const fs = require('fs');
				const ssi = require('ssi');
				const baseDir = 'dist/';
				let pathname = require('url').parse(req.url).pathname;
				let filename = require('path').join(baseDir, pathname);

				let parser = new ssi(baseDir, baseDir, '/**/*.shtml', true);

				if (filename.indexOf('.html') > -1 && fs.existsSync(filename)) {
					res.end(parser.parse(filename, fs.readFileSync(filename, {
						encoding: 'utf8'
					})).contents);
				} else {
					next();
				}

			}
		}
	});
}


/**
 * @description 文件调整监听
 * @returns 
 */
exports.watchHandler = function () {
	const watch_html = ['src/pages/**/*.html','src/public/*.html','src/components/*.html'];
	const watch_scss = ['src/assets/**/*.scss','src/pages/**/*.scss']
	gulp.watch(watch_scss, scssHandler),
	gulp.watch(handle_path['css'], cssHandler),
	gulp.watch(handle_path['js'], babelHandler),
	gulp.watch(handle_path['sprit'], spriteHandler),
	gulp.watch(handle_path['font'], fontsHandler)
	gulp.watch(handle_path['copy_lib'],libsHandler)
	gulp.watch(handle_path['copy_js'],copyJsHandler)
	gulp.watch(handle_path['copy_img'], copyImgHandler);
	gulp.watch(handle_path['copy_ficon'],copyFavHandler)
	gulp.watch(watch_html, htmlHandler)
	//监控src目录，刷新浏览器
	//编译后的目录放在dist目录
	let watcher = gulp.watch(['src']);
	watcher.on('change', () => {
		browserSync.reload();
	})
}